<template>
  <div class="pagination" v-if="total">
    <button @click="$emit('getPageNo', 1)">首页</button>
    <button :disabled="pageNo === 1" @click="$emit('getPageNo', pageNo - 1)">上一页</button>

    <!--  循环渲染当前页码前后连续的页码号、最多显示5个 -->
    <button v-for="num in startEndNumberCont" :key="num" :class="{ 'active': pageNo === num }"
      @click="$emit('getPageNo', num)">
      {{ num }}
    </button>

    <button @click="$emit('getPageNo', totalPages)">...</button>
    <button :disabled="pageNo === totalPages" @click="$emit('getPageNo', pageNo + 1)">下一页</button>
    <button style="margin-left: 30px">第{{ pageNo }}页/共{{ totalPages }}页</button>
    <button>共{{ total }}条</button>
    <!-- 跳转到指定页码 -->
    <input type="number" v-model="jumpPage" placeholder="页码" class="jump-page">
    <button @click="$emit('getPageNo', jumpPage)"> 跳转 </button>

  </div>
</template>

<script>
export default {
  name: 'PagesIndex',
  props: ['pageNo', 'pageSize', 'total', 'continues'],
  data() {
    return {
      jumpPage: ''
    }
  },
  computed: {
    // 计算总页数
    totalPages() {
      return Math.ceil(this.total / this.pageSize); // 向上取整
    },
    // 计算当前页码前后连续的页码号
    startEndNumberCont() {
      let start = this.pageNo - Math.floor(this.continues / 2);
      let end = start + this.continues - 1;
      if (end > this.totalPages) {
        end = this.totalPages;
        start = end - this.continues + 1;
      }
      if (start < 1) {
        start = 1;
        end = start + this.continues - 1;
      }
      return Array.from({ length: end - start + 1 }, (_, i) => start + i);
    }

  }
}
</script>

<style scoped>
.pagination {
  display: flex;
  align-content: center;
  justify-content: center;
  margin: 30px 0px;
}

button {
  display: inline-block;
  min-width: 40px;
  margin: 0px 5px;
  padding: 0px 8px;
  color: #353535;
  line-height: 28px;
  font-size: 16px;
  text-align: center;
  background-color: #f4f4f4;
  border: 1px solid #e2e2e2;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.3s ease;
}

button:hover {
  background-color: #f1463d;
  color: #fff;
}

button.active {
  background-color: rgb(72, 197, 247);
  color: #fff;
}

.jump-page {
  width: 50px;
  height: 28px;
  outline: none;
  border: 1px solid #ccc;
  border-radius: 3px;
}
</style>